import Config from '@/config'
import request from '@/libs/request';

export default {
	//文件上传
	uploadFile: (filePath, fileName = '', suffix = '/upload') => {
		return new Promise((resolve, reject) => {
			uni.showLoading({
				title: `加载中...`
			})
			const apiUrl = process.env.NODE_ENV === 'development' ? Config.baseUrl.dev : Config.baseUrl
				.prod
			const uploadUrl = `${apiUrl}${suffix}`
			console.log(uploadUrl)
			const loginRes = uni.getStorageSync('loginRes')
			const token = loginRes ? loginRes.token : ''
			const header = suffix === '/upload' ? {
				'content-type': 'multipart/form-data'
			} : {
				'authorization': token
			}
			console.log("fileName: ", fileName)
			const uploadTask = uni.uploadFile({
				url: uploadUrl,
				header,
				filePath,
				// name: 'fileUpload',
				name: fileName,
				success: (res) => {
					console.log('uploadFile: ', res, typeof res.data)
					if (res.statusCode === 200) {
						if (typeof res.data === 'string') {
							const data = JSON.parse(res.data)
							uni.showToast({
								title: data.message,
								icon: data.code === 100 ? 'success' : 'none'
							})
							resolve(data)
						} else {
							uni.showToast({
								title: res.data.message,
								icon: res.data.code === 100 ? 'success' : 'none'
							})
							resolve(res.data)
						}
					}
				},
				fail: (err) => {
					console.log(err)
					reject(err)
				},
				complete: () => {
					uni.hideLoading()
				}
			})

			console.log('uploadTask: ', uploadTask)

			// #ifndef MP-ALIPAY || MP-DINGTALK
			uploadTask.onProgressUpdate((task) => {
				console.log('上传进度', task.progress)
				console.log('已经上传的数据长度', task.totalBytesSent)
				console.log('预期需要上传的数据总长度', task.totalBytesExpectedToSend)
			})
			// #endif
		})
	},
	//文件下载
	downloadFile: url => {
		const downloadUrl = process.env.NODE_ENV === 'development' ? Config.baseUrl.dev : Config.baseUrl.prod
		console.log('downloadFile: ', downloadUrl + url)

		return new Promise((resolve, reject) => {
			uni.downloadFile({
				url: downloadUrl + url,
				header: {
					'authorization': uni.getStorageSync('loginRes').token || ''
				},
				success: res => {
					console.log('downloadFile success: ', res)
					resolve(res.tempFilePath || res.filePath);
				},
				fail: err => {
					console.log('downloadFile fail: ', err)
					reject(err)
				}
			})
		})
	},
	//文件下载
	downloadFileFromSite: url => {
		console.log("downloadFileFromSite: ", url)
		return new Promise((resolve, reject) => {
			uni.downloadFile({
				url,
				header: {},
				success: res => {
					console.log('downloadFile success: ', res)
					resolve(res.tempFilePath || res.filePath);
				},
				fail: err => {
					console.log('downloadFile fail: ', err)
					reject(err)
				}
			})
		})
	}
}